#include "client_communication.h"
#include <QTcpSocket>
#include <QTimer>

ClientCommunication::ClientCommunication(const QString ip, const unsigned short port)
    : Client(ip, port)
{
    client_socket_ = new QTcpSocket(this);
    connect(client_socket_, &QTcpSocket::readyRead, this, &ClientCommunication::onReadData);

    connect(this, &ClientCommunication::sigStartTimer, this, &ClientCommunication::onCreateTimer);
}

ClientCommunication::~ClientCommunication()
{
    delete client_socket_;
}

void ClientCommunication::setEngine(SystemInput *input)
{
    stystem_input_.reset(input);
    connect(this, &ClientCommunication::sigReadData, stystem_input_.get(), &SystemInput::dataInput);
}

void ClientCommunication::startScanServer()
{
    emit sigStartTimer();
}

void ClientCommunication::onConnectServer()
{
    client_socket_->connectToHost(camera_ip_, camera_port_);
    if(client_socket_->waitForConnected(1000)){
        monitor_connect_time_->stop();
        qDebug()<<"connect sucess";
    }
}

void ClientCommunication::onReadData()
{
    emit sigReadData(client_socket_->readAll());
}

void ClientCommunication::onWritData(const QByteArray data)
{
    long long res = client_socket_->write(data);
    client_socket_->flush();
    if(res == -1){
        qDebug()<<"write wrong"  << "disconnect";
        if(!monitor_connect_time_->isActive())
            monitor_connect_time_->start();
    }
}

void ClientCommunication::onCreateTimer()
{
    monitor_connect_time_ = new QTimer;
    connect(monitor_connect_time_, &QTimer::timeout, this, &ClientCommunication::onConnectServer);
    monitor_connect_time_->start(1000);
}
